package org.opensource.yabts.server;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Size;

import org.opensource.yabts.client.AuthService;
import org.opensource.yabts.shared.FieldVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
@Service("authService")
public class AuthServiceImpl extends RemoteServiceServlet implements AuthService {
	
	@Autowired
	private AuthenticationManager authenticationManager;

	public void doLogin(String username, String password) throws IllegalArgumentException {
		Authentication authenticationToken = new UsernamePasswordAuthenticationToken(username, password);

		// validate fields
		if (!FieldVerifier.isValidName(username)) {
			throw new RuntimeException("Username must be at least 4 characters long");
		}
		// authentication
	    try {
	    	SessionHelper.authenticateUser(authenticationManager.authenticate(authenticationToken));
	    } catch(BadCredentialsException e) {
			throw new RuntimeException("Username or password are incorrect");	    	
	    } catch (Exception e) {
	    	
		}
	}

	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
}
